//
//  ToolClass.m
//  SocketDemo
//
//  Created by apple on 17/2/24.
//  Copyright © 2017年 Apple. All rights reserved.
//

#import "ToolClass.h"
#import <sys/utsname.h>
#import <CoreLocation/CoreLocation.h>  
#import <UserNotifications/UserNotifications.h>


@implementation ToolClass

+(UILabel *)creatLabelWithFrame:(CGRect)frame font:(CGFloat)font textColor:(UIColor *)textColor text:(NSString *)text{
    UILabel * label = [[UILabel alloc]initWithFrame:frame];
    label.font = LYPFONT(font);
    label.textColor = textColor;
    label.numberOfLines = 0;
    label.text =text;
    return label;
}

+(UINavigationController *)getMainNavigationController{
    UINavigationController * mainNav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    return mainNav;
}


+(UIButton *)createButtonWithFrame:(CGRect)frame text:(NSString *)text textColor:(UIColor *)textColor imageName:(NSString *)imageName font:(CGFloat)font{
    UIButton * button = [[UIButton alloc]initWithFrame:frame];
    if (imageName.length > 0 && text.length > 0) {
        CGSize size = [text boundingRectWithSize:CGSizeMake(frame.size.width, frame.size.height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:font]} context:nil].size;
        CGFloat beginX = (frame.size.width - (size.width + [UIScreen zj_screenWith] * 0.02 + size.height * 1.6)) / 2;
        UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(beginX, (frame.size.height - size.height * 1.6) / 2, size.height * 1.6, size.height * 1.6)];
        imageView.image = [UIImage imageNamed:imageName];
        [button addSubview:imageView];
        
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake((CGRectGetMaxX(imageView.frame) + [UIScreen zj_screenWith] * 0.02), (frame.size.height - size.height) / 2, size.width, size.height)];
        if (textColor) {
            label.textColor = textColor;
        }
        label.font = LYPFONT(font);
        label.text = text;
        label.numberOfLines = 0;
        [button addSubview:label];
    }
    else{
        [button setTitle:text forState:UIControlStateNormal];
        if (textColor) {
            [button setTitleColor:textColor forState:UIControlStateNormal];
        }
        [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
        button.titleLabel.font = LYPFONT(font);
    }
    return button;
}



+(UIButton *)createButtonWithFrame:(CGRect)frame text:(NSString *)text textColor:(UIColor *)textColor imageName:(NSString *)imageName font:(CGFloat)font imageSize:(CGFloat)imageSize{
    UIButton * button = [[UIButton alloc]initWithFrame:frame];
    if (imageName.length > 0 && text.length > 0) {
        CGSize size = [text boundingRectWithSize:CGSizeMake(frame.size.width, frame.size.height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:font]} context:nil].size;
        CGFloat beginX = (frame.size.width - (size.width + [UIScreen zj_screenWith] * 0.02 + imageSize)) / 2;
        UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(beginX, (frame.size.height - imageSize) / 2, imageSize, imageSize)];
        imageView.image = [UIImage imageNamed:imageName];
        [button addSubview:imageView];
        
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake((CGRectGetMaxX(imageView.frame) + [UIScreen zj_screenWith] * 0.02), (frame.size.height - size.height) / 2, size.width, size.height)];
        if (textColor) {
            label.textColor = textColor;
        }
        label.font = LYPFONT(font);
        label.text = text;
        label.numberOfLines = 0;
        [button addSubview:label];
    }
    else{
        [button setTitle:text forState:UIControlStateNormal];
        if (textColor) {
            [button setTitleColor:textColor forState:UIControlStateNormal];
        }
        [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
        button.titleLabel.font = LYPFONT(font);
    }
    return button;
}


//上下结构的button
+(UIButton *)createUpDownButtonWithFrame:(CGRect)frame text:(NSString *)text textColor:(UIColor *)textColor imageName:(NSString *)imageName font:(CGFloat)font imageSize:(CGFloat)imageSize theInterval:(CGFloat)theInterval{
    UIButton * button = [[UIButton alloc]initWithFrame:frame];
    if (imageName.length > 0 && text.length > 0) {
        CGSize size = [text boundingRectWithSize:CGSizeMake(frame.size.width, frame.size.height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:font]} context:nil].size;
        CGFloat beginY = (frame.size.height - (size.height + theInterval + imageSize)) / 2;
        UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake((frame.size.width - imageSize) / 2, beginY, imageSize, imageSize)];
        imageView.image = [UIImage imageNamed:imageName];
        [button addSubview:imageView];
        
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake((frame.size.width - size.width) / 2, beginY + imageSize + theInterval, size.width, size.height)];
        if (textColor) {
            label.textColor = textColor;
        }
        label.font = LYPFONT(font);
        label.text = text;
        label.tag = 110;
        label.numberOfLines = 0;
        label.textAlignment = NSTextAlignmentCenter;
        [button addSubview:label];
    }
    else{
        [button setTitle:text forState:UIControlStateNormal];
        if (textColor) {
            [button setTitleColor:textColor forState:UIControlStateNormal];
        }
        [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
        button.titleLabel.font = LYPFONT(font);
    }
    return button;
}


+(UIImageView *)createRadiusImageViewWirhFrame:(CGRect)frame{
    UIImageView * imageView  = [[UIImageView alloc] initWithFrame:frame];
    imageView.clipsToBounds = YES;
    imageView.layer.cornerRadius = frame.size.height / 2;
    return imageView;
}



+(UIButton *)createSystemButtonWithOriginY:(CGFloat)originY text:(NSString *)text{
    UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake([UIScreen zj_screenWith] * 0.03 , originY, [UIScreen zj_screenWith] * 0.94 , [UIScreen zj_screenHeight] * 0.056)];
    [button setTitle:text forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button.titleLabel.font = LYPFONT(15);
    button.layer.cornerRadius = [UIScreen zj_screenHeight] * 0.028;
    return button;
}

+(UIButton *)createSystemBoraderButtonWithFrame:(CGRect)frame text:(NSString *)text{
    UIButton * button = [[UIButton alloc]initWithFrame:frame];
    [button setTitle:text forState:UIControlStateNormal];
    button.titleLabel.font = LYPFONT(15);
    button.backgroundColor = [UIColor whiteColor];
    button.layer.cornerRadius = frame.size.height / 2;
    button.layer.borderWidth = 0.5;
    return button;
}

+(NSString *)getChineseStringByNumber:(NSNumber *)number{
    NSNumberFormatter * formatter = [[NSNumberFormatter alloc]init];
    [formatter setNumberStyle:NSNumberFormatterSpellOutStyle];
    return [formatter stringFromNumber:number];
}



+(UITextField *)createTextFieldWithFrame:(CGRect)frame placeholder:(NSString *)placeholder{
    UITextField * textField = [[UITextField alloc]initWithFrame:frame];
    textField.placeholder = placeholder;
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen zj_screenWith] * 0.05, frame.size.height)];
    textField.clipsToBounds = YES;
    textField.layer.cornerRadius = frame.size.height / 2;
    textField.font = LYPFONT(14);
    return textField;
    
}

+(UIViewController *)findViewControllerWithCurrentView:(UIView *)currentView{
    for (UIView * view = currentView; view; view = view.superview) {
        if ([view.nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)view.nextResponder;
        }
    }
    return nil;
}

+(UITabBarController *)getMainTabBarViewController{
    UINavigationController * nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    __block UITabBarController * vc;
    [nav.viewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isMemberOfClass:[UITabBarController class]]) {
            vc = (UITabBarController *)obj;
        }
    }];
    return vc;
}

+(CGFloat)widthOfString:(NSString *)string font:(UIFont *)font height:(CGFloat)height
{
    NSDictionary * dict=[NSDictionary dictionaryWithObject: font forKey:NSFontAttributeName];
    CGRect rect=[string boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];
    return rect.size.width;
}


+ (BOOL)openMessageNotificationService
{
    BOOL isOpen = NO;
    UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
    if (setting.types != UIUserNotificationTypeNone) {
        isOpen = YES;
    }
    return isOpen;
}


+ (BOOL)openLocationService
{
    BOOL isOPen = NO;
    if ([CLLocationManager locationServicesEnabled] && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied) {
        isOPen = YES;
    }
    return isOPen;
}



+ (NSString *)iphoneType {
    
    
    struct utsname systemInfo;
    
    uname(&systemInfo);
    
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
    
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
    
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
    
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
    
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
    
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
    
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";
    
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";
    
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";
    
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";
    
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
    
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    
    if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
    
    if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone 7";
    
    if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus";
    
    if ([platform isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G";
    
    if ([platform isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G";
    
    if ([platform isEqualToString:@"iPod3,1"])   return @"iPod Touch 3G";
    
    if ([platform isEqualToString:@"iPod4,1"])   return @"iPod Touch 4G";
    
    if ([platform isEqualToString:@"iPod5,1"])   return @"iPod Touch 5G";
    
    if ([platform isEqualToString:@"iPad1,1"])   return @"iPad 1G";
    
    if ([platform isEqualToString:@"iPad2,1"])   return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,2"])   return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,3"])   return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,4"])   return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,5"])   return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad2,6"])   return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad2,7"])   return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad3,1"])   return @"iPad 3";
    
    if ([platform isEqualToString:@"iPad3,2"])   return @"iPad 3";
    
    if ([platform isEqualToString:@"iPad3,3"])   return @"iPad 3";
    
    if ([platform isEqualToString:@"iPad3,4"])   return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad3,5"])   return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad3,6"])   return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad4,1"])   return @"iPad Air";
    
    if ([platform isEqualToString:@"iPad4,2"])   return @"iPad Air";
    
    if ([platform isEqualToString:@"iPad4,3"])   return @"iPad Air";
    
    if ([platform isEqualToString:@"iPad4,4"])   return @"iPad Mini 2G";
    
    if ([platform isEqualToString:@"iPad4,5"])   return @"iPad Mini 2G";
    
    if ([platform isEqualToString:@"iPad4,6"])   return @"iPad Mini 2G";
    
    if ([platform isEqualToString:@"i386"])      return @"iPhone Simulator";
    
    if ([platform isEqualToString:@"x86_64"])    return @"iPhone Simulator";
    
    return platform;
    
}





+(NSData *)getDataFromDictionary:(NSDictionary *)dic{
    NSError * error = nil;
    NSString * jsonString = @"";
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSData * data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    return data;
}

+(NSString *)getjsonStringFromDictionary:(NSDictionary *)dic{
    NSError * error = nil;
    NSString * jsonString = @"";
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}

+(NSDictionary *)getDictionaryFromJsonString:(NSString *)jsonString{
    if (jsonString.length > 0) {
        NSError * error = nil;
        NSData * data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary * dic =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        return dic;
    }
    else{
        return @{};
    }
}




+(void)loginOutCleanData{
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"imid"];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"imnickname"];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"token"];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"uid"];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"updatekey"];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"imhead"];
    [[NSUserDefaults standardUserDefaults] setObject:@"NO" forKey:@"isLogin"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"LoginOutNotification" object:nil userInfo:nil];
}





+(void)cleanCacheAndCookie{
    //清除cookies
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies]){
        [storage deleteCookie:cookie];
    }
    //清除UIWebView的缓存
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];
}

//邮箱
+ (BOOL) justEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}


//手机号码验证
+ (BOOL) justMobile:(NSString *)mobile
{
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}


//车牌号验证
+ (BOOL) justCarNo:(NSString *)carNo
{
    NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    NSLog(@"carTest is %@",carTest);
    return [carTest evaluateWithObject:carNo];
}


//车型
+ (BOOL) justCarType:(NSString *)CarType
{
    NSString *CarTypeRegex = @"^[\u4E00-\u9FFF]+$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CarTypeRegex];
    return [carTest evaluateWithObject:CarType];
}


//用户名
+ (BOOL) justUserName:(NSString *)name
{
    //(^[a-zA-Z_0-9]{3,30}$)
    NSString *userNameRegex = @"^[A-Za-z0-9]{3,30}+$";
    NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
    BOOL B = [userNamePredicate evaluateWithObject:name];
    return B;
}


//密码
+ (BOOL) justPassword:(NSString *)passWord
{
    //(^[\\s\\S]{6,30}$)
    
    //  NSString *passWordRegex = @"^[a-zA-Z0-9]{6,20}+$";
    NSString *passWordRegex = @"^[\\s\\S]{6,30}$";
    
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    return [passWordPredicate evaluateWithObject:passWord];
}


//昵称
+ (BOOL) justNickname:(NSString *)nickname
{
    //(^[a-zA-Z0-9]{2,30}$)|(^[a-zA-Z0-9\u4E00-\u9FA5]{2,10}$)
    // NSString *nicknameRegex = @"^[\u4e00-\u9fa5]{4,8}$";
    
    NSString *nicknameRegex =@"(^[a-zA-Z0-9]{2,30}$)|(^[a-zA-Z0-9\u4E00-\u9FA5]{2,10}$)";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
    return [passWordPredicate evaluateWithObject:nickname];
}


//身份证号
+ (BOOL) justIdentityCard: (NSString *)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
}


//获取版本号
+(NSString *)getCurrentVersion{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString * app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return app_Version;
}


//压缩图片至多少b
//image:压缩的图片   compressionMaxLimit:压缩最大限制
+(NSData *)compressionImageWithImage:(UIImage *)image compressionMaxLimit:(CGFloat)compressionMaxLimit{
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length > compressionMaxLimit)
    {
        CGFloat max = 1;
        CGFloat min = 0;
        for (int i = 0; i < 6; ++i) {
            compression = (max + min) / 2;
            data = UIImageJPEGRepresentation(image, compression);
            if (data.length < compressionMaxLimit * 0.9) {
                min = compression;
            } else if (data.length > compressionMaxLimit) {
                max = compression;
            } else {
                break;
            }
        }
    }
    return data;
}

@end
